package com.wlsk.license.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wlsk.license.common.constant.CharteredLicenseConstant;
import com.wlsk.license.common.enums.CharterPlateProductTypeEnum;
import com.wlsk.license.common.enums.CharterPlateStatusEnum;
import com.wlsk.license.common.enums.RePrintStatusEnum;
import com.wlsk.license.common.utils.DateUtils;
import com.wlsk.license.dao.entity.Plate;
import com.wlsk.license.dao.entity.ReprintTask;
import com.wlsk.license.dao.entity.SysRegion;
import com.wlsk.license.dto.response.CityCodeResulitDto;
import com.wlsk.license.dto.zz.LicenseInfoDto;
import com.wlsk.license.dto.zz.SelectStateReqDto;
import com.wlsk.license.service.IPlateService;
import com.wlsk.license.service.IReprintTaskService;
import com.wlsk.license.service.ISysRegionService;
import com.wlsk.license.service.ITaskService;
import com.wlsk.license.service.zpff.CharterApplyLicense;
import com.wlsk.license.service.zpff.CharterApplyService;
import com.zhongjinfeng.util.helper.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TaskServiceImpl implements ITaskService {

    @Autowired
    private IPlateService plateService;

    @Autowired
    private ISysRegionService sysRegionService;

    @Autowired
    private IReprintTaskService reprintTaskService;

    @Autowired
    private CharterApplyService applyService;

    @Override
    public void taskSelectState() {
        List<Integer> statusList = Lists.list(
                CharterPlateStatusEnum.REVIEW.getCode(),
                CharterPlateStatusEnum.REVIEWED.getCode(),
                CharterPlateStatusEnum.GENERATED.getCode(),
                CharterPlateStatusEnum.ARCHIVED.getCode(),
                CharterPlateStatusEnum.REPRINT.getCode(),
                CharterPlateStatusEnum.REFILL.getCode());
        Date applyTime = DateUtils.addDays(new Date(), -60);
        List<Plate> reviewList = plateService.getBaseMapper().selectList(Wrappers.<Plate>lambdaQuery().eq(Plate::getDelFlag, 0).ge(Plate::getApplyTime, applyTime).in(Plate::getCharterPlateStatus, statusList));
        if (CollectionUtils.isNotEmpty(reviewList)) {
            for (Plate plate : reviewList) {
                try {
                    LicenseInfoDto licenseInfo = applyService.selectState(SelectStateReqDto.builder().appnumber(plate.getTradeAppNumber()).build());
                    if (licenseInfo != null) {
                        String state = licenseInfo.getState();
                        if (state != null) {
                            plate.setTradeCharterPlateStatus(Integer.parseInt(state));
                            CharterPlateStatusEnum statusEnum = CharteredLicenseConstant.PLATE_TRADE_STATUS.get(Integer.parseInt(state));
                            if (statusEnum != null && !statusEnum.getCode().equals(plate.getCharterPlateStatus())) {
                                plate.setCharterPlateStatus(statusEnum.getCode());
                                if(StringUtils.isNotEmpty(licenseInfo.getPrintLicNo())) {
                                    plate.setCharterPlateNumber(licenseInfo.getPrintLicNo());
                                }
                                if(licenseInfo.getPrintLicPlaID() != null) {
                                    plate.setPrintLicPlaId(licenseInfo.getPrintLicPlaID());
                                }
                            } else {
                                log.error("包车牌状态枚举不存在,{}-{}", plate.getTradeAppNumber(), licenseInfo);
                            }
                            plateService.updateById(plate);
                        }
                    }
                } catch (Exception e) {
                    log.error("审核包车牌异常", e);
                }
            }
        }
    }

    @Override
    public void clearPlate() {
        try {
            log.info("开始执行包车牌草稿数据清理任务");
            // 计算30天前的时间
            LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);

            // 查询30天前的草稿数据
            List<Plate> expiredPlates = plateService.getBaseMapper().selectList(
                    new LambdaQueryWrapper<Plate>()
                            .eq(Plate::getDelFlag, "0")  // 未删除的数据
                            .eq(Plate::getCharterPlateStatus, CharterPlateStatusEnum.DRAFT.getCode())  // 草稿状态
                            .lt(Plate::getApplyTime, thirtyDaysAgo)  // 申请时间超过30天
            );

            if (expiredPlates.isEmpty()) {
                log.info("没有需要清理的过期包车牌草稿数据");
                return;
            }
            log.info("找到 {} 条过期的包车牌草稿数据，开始清理", expiredPlates.size());
            // 批量更新删除标志
            int updatedCount = 0;
            for (Plate plate : expiredPlates) {
                plate.setDelFlag("1");
                plate.setUpdateTime(LocalDateTime.now());
                //TODO 2025/10/21 推送运管删除草稿
                if (!StringHelper.isEmpty(plate.getTradeAppNumber())) {
                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("appNumber", plate.getTradeAppNumber());
                    Map<String, String> stringStringMap = CharterApplyLicense.gainCharterLicenseData(JSON.toJSONString(jsonParam), CharterApplyLicense.MTA_DELETE_DRAFT);
                    log.info("运管系统执行删除编号为{} 的包车牌草稿数据，结果{}", plate.getTradeAppNumber(), stringStringMap.get("data"));
                }
                int result = plateService.getBaseMapper().updateById(plate);
                if (result > 0) {
                    updatedCount++;
                }
            }
            log.info("成功清理 {} 条过期的包车牌草稿数据", updatedCount);
        } catch (Exception e) {
            log.error("执行包车牌草稿数据清理任务时发生异常", e);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void cityCoderefresh() {
        Map<String, Object> paramMap = new HashMap<>();
        // 获取省// 获取省
        paramMap.put("cLevel", "00550001");
        paramMap.put("id", "");

        //TODO 2025/10/21 1、获取省
        //循环省获取 省市
        Map<String, String> map = CharterApplyLicense.gainCharterLicenseData(JSON.toJSONString(paramMap), CharterApplyLicense.GET_CITIESDJ);
        if ("200".endsWith(map.get("code"))) {
            // TODO: 2025/9/24 后续可以加上保存到数据库，防止每次去请求
            CityCodeResulitDto data = JSON.parseObject(map.get("data"), CityCodeResulitDto.class);
            log.info("省" + data.getCities().size() + "条");
            for (SysRegion city : data.getCities()) {
                sysRegionService.saveOrUpdate(city);
                paramMap.put("cLevel", "");
                paramMap.put("id", city.getCXzqhId());
                //TODO 2025/10/21 2、获取市
                map = CharterApplyLicense.gainCharterLicenseData(JSON.toJSONString(paramMap), CharterApplyLicense.GET_CITIESDJ);
                if ("200".endsWith(map.get("code"))) {
                    data = JSON.parseObject(map.get("data"), CityCodeResulitDto.class);
                    if (data.getCities() != null && data.getCities().size() > 0) {
                        sysRegionService.saveOrUpdateBatch(data.getCities(), 100);
                        log.info(city.getCName() + "市" + data.getCities().size() + "条");
                    }
                }
            }
            log.error("每天定时更新行政区划成功");
        }
    }

    /**
     * 每天定时扫描数据将
     */
    @Override
    public void platePrintSupplement() {
        List<Plate> plates = plateService.getBaseMapper().selectList(new LambdaQueryWrapper<Plate>().eq(Plate::getTradeCharterPlateStatus, CharteredLicenseConstant.TRADE_PLATE_STATUS.get(CharterPlateStatusEnum.GENERATED))
                .eq(Plate::getCharterPlateStatus, CharterPlateStatusEnum.PRINTED.getCode())
                .eq(Plate::getPlateProduceType, CharterPlateProductTypeEnum.PAPER_CHARTER_PLATE.getCode())
                .eq(Plate::getPrintSupplementStatus, RePrintStatusEnum.NOT_RECORDED.getCode()));
        plates.stream().forEach(plate -> {
            ReprintTask reprintTask = reprintTaskService.getBaseMapper().selectById(plate.getId());
            if (reprintTask == null) {
                reprintTask = new ReprintTask();
                reprintTask.setId(plate.getId());
                reprintTask.setLastRetryTime(1L);
                reprintTask.setRetryCount(0);
                reprintTask.setStatus(0);
                reprintTaskService.getBaseMapper().insert(reprintTask);
            }
        });
    }
}
